﻿using Microsoft.EntityFrameworkCore;
using MyMES.Dto;
using MyMES.IServices.MeadingManage;
using MyMes.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Extensions;
using VOL.Core.Utilities.Response;
using VOL.Entity.DomainModels.Core;
using VOL.Entity.MeadingManage;

namespace MyMES.Services.MeadingManage
{
    public class WorkOrderService : IWorkOrderService
    {
        private readonly IBaseRepository<WorkOrder> _workOrderRepository;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workOrderRepository">工单仓储接口</param>
        public WorkOrderService(IBaseRepository<WorkOrder> workOrderRepository)
        {
            _workOrderRepository = workOrderRepository;
        }
        
        /// <summary>
        /// 创建工单
        /// </summary>
        /// <param name="workOrder">工单信息</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> CreateWorkOrder(WorkOrder workOrder)
        {
            // 创建响应对象
            WebResponseContent response = new WebResponseContent();
            
            try
            {
    
                // 保存到数据库
                int result = await _workOrderRepository.AddAsync(workOrder);
                
                if (result > 0)
                {
                    return response.OK("工单创建成功", workOrder);
                }
                else
                {
                    return response.Error("工单创建失败");
                }
            }
            catch (Exception ex)
            {
                return response.Error($"创建工单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="ids">工单ID，多个ID用逗号分隔</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> DelWorkOrder(string ids)
        {
            WebResponseContent response = new WebResponseContent();
            
            try
            {

                
                // 解析ID列表
                List<int> idList = ids.Split(',').Select(int.Parse).ToList();
                
                // 从数据库中删除指定ID的工单
                int result = await _workOrderRepository.DelAll(w => idList.Contains(w.Id));
                
                if (result > 0)
                {
                    return response.OK($"成功删除{result}个工单");
                }
                else
                {
                    return response.Error("删除失败，请稍后重试");
                }
            }
            catch (Exception ex)
            {
                return response.Error($"删除工单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取工单列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>工单列表</returns>
        public async Task<PageGridData<WorkOrder>> GetWorkOrder(GetWorkOrderPageDto dto)
        {
            PageGridData<WorkOrder> pageData = new PageGridData<WorkOrder>();
            
            try
            {
                // 构建查询
                var query = _workOrderRepository.GetAll();
                
                // 应用筛选条件
                query = query.WhereIF(!string.IsNullOrEmpty(dto.WorkOrderCode), 
                    w => w.WorkOrderCode.Contains(dto.WorkOrderCode));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.WorkOrderName), 
                    w => w.WorkOrderName.Contains(dto.WorkOrderName));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.WorkOrderSource), 
                    w => w.WorkOrderSource.Contains(dto.WorkOrderSource));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.ProductNumber), 
                    w => w.ProductNumber.Contains(dto.ProductNumber));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.ProductName), 
                    w => w.ProductName.Contains(dto.ProductName));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.ClientCode), 
                    w => w.ClientCode.Contains(dto.ClientCode));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.ClientName), 
                    w => w.ClientName.Contains(dto.ClientName));
                
                query = query.WhereIF(!string.IsNullOrEmpty(dto.WorkOrderType), 
                    w => w.WorkOrderType.Contains(dto.WorkOrderType));
                
                query = query.WhereIF(dto.NeedsDate.HasValue, 
                    w => w.NeedsDate.Date == dto.NeedsDate.Value.Date);
                
                // 获取总记录数
                int totalCount = await query.CountAsync();
                
                // 分页并获取数据
                int pageIndex = dto.PageIdnex <= 0 ? 1 : dto.PageIdnex;
                int pageSize = dto.PageSize <= 0 ? 10 : dto.PageSize;
                
                var workOrders = await query
                    .OrderByDescending(w => w.Id)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();
                
              
                
                // 设置返回数据
                pageData.status = 1;
                pageData.msg = "获取成功";
                pageData.total = totalCount;
                pageData.rows = workOrders;
                
                return pageData;
            }
            catch (Exception ex)
            {
                pageData.status = 0;
                pageData.msg = $"获取工单列表失败：{ex.Message}";
                pageData.rows = new List<WorkOrder>();
                return pageData;
            }
        }

        /// <summary>
        /// 更新工单
        /// </summary>
        /// <param name="workOrder">工单信息</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdateWorkOrder(WorkOrder workOrder)
        {
            WebResponseContent response = new WebResponseContent();
            
            try
            {
                // 更新数据库中的工单信息
                int result = await _workOrderRepository.UpdateAsync(workOrder);
                
                if (result > 0)
                {
                    return response.OK("工单更新成功", workOrder);
                }
                else
                {
                    return response.Error("工单更新失败");
                }
            }
            catch (Exception ex)
            {
                return response.Error($"更新工单失败：{ex.Message}");
            }
        }
    }
}
